<?php

/**
 * search actions.
 *
 * @package    sfwixet
 * @subpackage search
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class searchActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
			
  	
			if($request->getParameter("searchin")=="friendlist"){
				$q = Doctrine_Query::create()
				->select('a.user_id')
				->from('AclUsersGroups a')
				->leftJoin('a.user u')
				->addWhere('a.group_id = ?',$this->getUser()->getGuardUser()->getMainAlbumId());
			}else{
				$q = Doctrine_Query::create()
				->select('s.user_id')
				->from('SearchProfile s')
				->leftJoin('s.user u')
				->addWhere('s.user_id <> ?',$this->getUser()->getId());
			}
				
			if(is_numeric($request->getParameter("agemin"))){
				$q->addWhere("EXTRACT(YEAR FROM now()) - EXTRACT(YEAR FROM birthday) >= ?",$request->getParameter("agemin"));
			}
			
  			if(is_numeric($request->getParameter("agemax"))){
				$q->addWhere("EXTRACT(YEAR FROM now()) - EXTRACT(YEAR FROM birthday) <= ?",$request->getParameter("agemax"));
			}
			
  			if(is_numeric($request->getParameter("city"))){
				$q->addWhere("s.city_id = ?",$request->getParameter("city"));
			}
			
  			if(is_numeric($request->getParameter("country"))){
				$q->addWhere("s.country_id = ?",$request->getParameter("country"));
			}
			
  			if(is_numeric($request->getParameter("gender"))){
				$q->addWhere("s.gender = ?",$request->getParameter("gender"));
			}
			
			//TODO aqui tambien se podría reducir el código, cuando se haga en el cliente
  			$places = json_decode($request->getParameter("place"));
			if(count($places) > 0){
				$q->leftJoin('s.placeUser pu');	
				foreach($places as $place){
					$q->addWhere("pu.place_id = ?",$place);
				}
			}
			
  			$schools = json_decode($request->getParameter("school"));
			if(count($schools) > 0){
				$q->leftJoin('s.schoolUser su');	
				foreach($schools as $school){
					$q->addWhere("su.school_id = ?",$school);
				}
			}
			
  			$workplaces = json_decode($request->getParameter("workplace"));
			if(count($workplaces) > 0){
				$q->leftJoin('s.workplaceUser wu');	
				foreach($workplaces as $workplace){
					$q->addWhere("wu.workplace_id = ?",$workplace);
				}
			}
			
  			$cityplaces = json_decode($request->getParameter("cityplace"));
			if(count($cityplaces) > 0){
				$q->leftJoin('s.cityUser cu');	
				foreach($cityplaces as $cityplace){
					$q->addWhere("cu.city_id = ?",$cityplace);
				}
			}
			//TODO hacer que tambien mire en el town
			$name = strtolower(str_replace(" ", "", trim($request->getParameter("name"))));
			if(strlen($name) > 0){
				$q->addWhere("levenshtein(lower(firstname),?) < 5".
							" OR levenshtein(lower(lastname),?) < 5".
							" OR levenshtein(lower(secondlastname),?) < 5".
							" OR levenshtein(lower(concat(firstname,lastname)),?) < 5".
							" OR levenshtein(lower(concat(firstname,lastname,secondlastname)),?) < 5",
							array($name,$name,$name,$name,$name));
			}
			
	$pager = new sfDoctrinePager('searchProfile',$request->getParameter("size",10));
	$pager->setQuery($q);
	
  	$pager->setPage($request->getParameter("page",1));
  	
  	$pager->init();
  	$users = array();
	foreach($pager->getResults() as $searchProfile){
		//Searching by friends
		try{
			$userArr = array();
			
			if($searchProfile instanceof aclUsersGroups){
				$user = $searchProfile->getUser();
				$searchProfile = $user->getProfile();
				$userArr['friend'] = true;
			}else{
				//All wixet search
				$user = $searchProfile->getUser();
				$userArr['friend'] = $user->isFriend($this->getUser());
			}
			
			$userArr['firstname'] = $user->getFirstname();
			$userArr['lastname'] = $user->getLastname();
			$userArr['secondLastname'] = $user->getSecondlastname();
			$userArr['id'] = $user->getId();
			$userArr['school'] = $searchProfile->getSchools()->toArray();
			$userArr['workplace'] = $searchProfile->getWorkplaces()->toArray();
			$userArr['city'] = $searchProfile->getCity()->toArray();
			$userArr['photo'] = $user->getMainPhotoId();
			
			$users[] = $userArr;
		}catch(Exception $e){
			//Forbidden user
		}
	}
	echo json_encode(array("users"=>$users,"pagecount"=>$pager->getLastPage()));
	return sfView::NONE;
  }
  
  public function executeSchool(sfWebRequest $request)
  {
  	$schools=array();
  	$q = Doctrine_Query::create()
			->select('s.school_id')
			->from('School s')
			->where('s.name LIKE ?',$request->getParameter("term")."%");

	foreach($q->execute() as $school){
		$schoolArr = array();
  		$schoolArr['id']=$school->getSchoolId();
  		$schoolArr['label']=$school->getName();
  		$schoolArr['value']=$school->getName();
 		$schools[]=$schoolArr;
	}
		
 	echo json_encode($schools);
 	return sfView::NONE;
  }
  
  public function executeWorkplace(sfWebRequest $request)
  {
  	$workplaces=array();
  	$q = Doctrine_Query::create()
			->select('w.workplace_id')
			->from('Workplace w')
			->where('w.name LIKE ?',$request->getParameter("term")."%");

	foreach($q->execute() as $workplace){
		$workplaceArr = array();
  		$workplaceArr['id']=$workplace->getWorkplaceId();
  		$workplaceArr['label']=$workplace->getName();
  		$workplaceArr['value']=$workplace->getName();
 		$workplaces[]=$workplaceArr;
	}
		
 	echo json_encode($workplaces);
 	return sfView::NONE;
  }
  
  public function executeTown(sfWebRequest $request)
  {
  	$towns=array();
  	$q = Doctrine_Query::create()
			->select('c.city_id')
			->from('City c')
			->where('c.name LIKE ? AND c.capital_id IS NOT NULL',$request->getParameter("term")."%");

	foreach($q->execute() as $town){
		$townArr = array();
  		$townArr['id']=$town->getCityId();
  		$townArr['label']=$town->getName();
  		$townArr['value']=$town->getName();
 		$towns[]=$workplaceArr;
	}
		
 	echo json_encode($towns);
 	return sfView::NONE;
  }
  
  public function executePlaceSimple(sfWebRequest $request)
  {
  	$places=array();
  	$q = Doctrine_Query::create()
			->select('p.place_id')
			->from('Place p')
			->where('p.name LIKE ?',$request->getParameter("term")."%");

	foreach($q->execute() as $place){
		$placeArr = array();
		$placeArr['type']="place";
  		$placeArr['id']=$place->getPlaceId();
  		$placeArr['label']=$place->getName();
  		$placeArr['value']=$place->getName();
 		$places[]=$placeArr;
	}
		
	//Also de non capital cities
    $q = Doctrine_Query::create()
			->select('c.city_id')
			->from('City c')
			->where('c.capital_id IS NOT NULL AND c.name LIKE ?',$request->getParameter("term")."%");

	foreach($q->execute() as $place){
		$placeArr = array();
		$placeArr['type']="city";
  		$placeArr['id']=$place->getCityId();
  		$placeArr['label']=$place->getName();
  		$placeArr['value']=$place->getName();
 		$places[]=$placeArr;
	}	
	
 	echo json_encode($places);
 	return sfView::NONE;
  }
  
  public function executeSound(sfWebRequest $request)
  {
  	$sounds=array();
  	$q = Doctrine_Query::create()
			->from('Sound s')
			->where('s.name LIKE ?',"%".$request->getParameter("term")."%");

	foreach($q->execute() as $sound){
		$soundArr = array();
  		$soundArr['id']=$sound->getSoundId();
  		$soundArr['label']=$sound->getName();
  		$soundArr['value']=$sound->getName();
 		$sounds[]=$soundArr;
	}
		
 	echo json_encode($sounds);
 	return sfView::NONE;
  }
  
  public function executeYoutube(sfWebRequest $request)
  {
  	$query = $request->getParameter("query");
  	try{
  	if($query == null) throw new Exception("Please provide a search query");
		$youtube = new YoutubeQuery();
		$youtube->setQuery($query);
		$youtube->setPageSize($request->getParameter("size",10));
		echo json_encode($youtube->getPage($request->getParameter("page",1)));
  	}catch(Exception $e){
  		json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}	
  	
 	
 	return sfView::NONE;
  }
}
